package com.ruoyi.ruoyiqywechat.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.qy.constants.Constants;
import com.ruoyi.common.qy.domain.User;
import com.ruoyi.common.qy.exception.CrmebException;
import com.ruoyi.common.qy.request.RegisterThirdUserRequest;
import com.ruoyi.common.qy.utils.CrmebUtil;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.ruoyiqywechat.dao.UserDao;
import com.ruoyi.ruoyiqywechat.handle.UnauthorizedException;
import com.ruoyi.ruoyiqywechat.service.UserService;
import io.jsonwebtoken.Claims;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户表 服务实现类
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    private UserDao userDao;
    @Override
    public User getByPhone(String phone) {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone, phone);
        return userDao.selectOne(lqw);
    }
    /**
     * 获取当前用户id
     *
     * @return Integer
     * @author Mr.Zhang
     * @since 2020-04-28
     */
    @Override
    public Long getUserId() {
        Long id = SecurityUtils.getUserId();
        if (null == id) {
            return 0l;
        }
        return id;
    }
    /**
     * 获取个人资料
     *
     * @return User
     * @author Mr.Zhang
     * @since 2020-04-28
     */
    @Override
    public User getInfoException() {
        User user = getInfo();
        if (user == null) {
            throw new CrmebException("用户信息不存在！");
        }

        if (!user.getStatus()) {
            throw new CrmebException("用户已经被禁用！");
        }
        return user;
    }

    @Override
    public boolean bindShareId(HttpServletRequest request, Integer shareId) {
        User user = getInfo();
        if (user == null) {
            throw new UnauthorizedException("用户不存在哦");
        }
        if(user.getUid().compareTo(shareId) == 0){
            throw new CrmebException("请扫好友分享码!");
        }
        //判断是否已经存在了绑定关系
        if(user.getSpreadUid() !=0 && user.getSpreadUid().compareTo(shareId) != 0){
            throw new CrmebException("已绑定其他分享者用户ID");
        }
        user.setSpreadUid(shareId);
        user.setSpreadTime(DateUtils.getNowDate());
        return userDao.updateById(user)>0;
    }

    @Override
    public PageInfo<User> querySpIdUserList(HttpServletRequest request,Integer pageNum,Integer pageSize) {
        Claims claims = JwtUtils.parseToken(SecurityUtils.getToken());
        String userid = JwtUtils.getUserId(claims);
        if(userid == null)throw new  CrmebException("用户不存在!");
        // 开启分页
        PageHelper.startPage(pageNum, pageSize);
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.lambda().eq(User::getSpreadUid,userid);
        List<User> userList = userDao.selectList(userQueryWrapper);
        PageInfo<User> userPageInfo = new PageInfo<>(userList);
        // 获取分页数据
//        List<User> list = userPageInfo.getList();// 当前页数据
//        long total = userPageInfo.getTotal();           // 总记录数
//        long pages = userPageInfo.getPages();           // 总页数
//        long current = userPageInfo.getPageNum();           // 当前页
//        long size = userPageInfo.getSize();                 // 每页大小
        return userPageInfo;
    }

    /**
     * 获取个人资料
     *
     * @return User
     * @author Mr.Zhang
     * @since 2020-04-28
     */
    @Override
    public User getInfo() {

        if (getUserId() == 0) {
            return null;
        }
        return getById(getUserId());
    }
    @Override
    public User registerByThird(RegisterThirdUserRequest thirdUserRequest) {
        User user = new User();
        user.setAccount(DigestUtils.md5Hex(CrmebUtil.getUuid() + DateUtils.getNowDate()));
        user.setUserType(thirdUserRequest.getType());
        user.setNickname(thirdUserRequest.getNickName());
        String avatar = "";
        switch (thirdUserRequest.getType()) {
            case Constants.USER_LOGIN_TYPE_PUBLIC:
                avatar = StrUtil.isBlank(thirdUserRequest.getHeadimgurl()) ? "" : thirdUserRequest.getHeadimgurl();
                break;
            case Constants.USER_LOGIN_TYPE_PROGRAM:
            case Constants.USER_LOGIN_TYPE_H5:
            case Constants.USER_LOGIN_TYPE_IOS_WX:
            case Constants.USER_LOGIN_TYPE_ANDROID_WX:
                avatar = StrUtil.isBlank(thirdUserRequest.getAvatar()) ? "" : thirdUserRequest.getAvatar();
                break;
        }
        user.setAvatar(avatar);
        user.setSpreadTime( DateUtils.getNowDate());
        // 因微信原因，无法再获取用户的隐私信息
        // 预设用户性别为0-未知，地址为空字符串
//        user.setSex(Integer.parseInt(thirdUserRequest.getSex()));
//        user.setAddres(thirdUserRequest.getCountry() + "," + thirdUserRequest.getProvince() + "," + thirdUserRequest.getCity());
        user.setSex(0);
        user.setAddres("");
        return user;
    }
}
